<template>
	<view>
		<!-- 导航栏 -->
		 <uni-nav-bar left-icon="left"  :statusBar="true" titleSize="30px" leftText="返回"    rightText="保存"  title="新增明细"   @clickLeft="back" @clickRight="btnOk"   :fixed="true" backgroundColor="#3286ed" color="#fff"/>
	
	<u--form class="form" labelPosition="left" labelWidth="100px" :model="form" :rules="rules"  ref="form">
		
		<u-form-item  label="单号" prop="serialNum" borderBottom ref="item1">
			<u--input :readonly="true" v-model="form.serialNum" border="none" placeholder="业务员名称"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
		</u-form-item>
		<u-form-item leftIcon="*" leftIconStyle="color:red;" label="租赁订单" prop="orderNo" borderBottom ref="item1" @click="openPop">
			<u--input :readonly="true" v-model="form.orderNo" border="none" placeholder="选择租赁订单"></u--input>
						<u-icon @click="openPop" slot="right" name="arrow-right"></u-icon>
		</u-form-item>
		<u-form-item leftIcon="*" leftIconStyle="color:red;" label="业务员名称" prop="salesmanName" borderBottom ref="item1">
			<u--input :readonly="true" v-model="form.salesmanName" border="none" placeholder="业务员名称"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
		</u-form-item>
		<u-form-item leftIcon="*" leftIconStyle="color:red;" label="发起人" prop="applicantName" borderBottom ref="item1">
			<u--input :readonly="true" v-model="form.applicantName" border="none" placeholder="业务员名称"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
		</u-form-item>
		
		<u-form-item leftIcon="*" leftIconStyle="color:red;" label="项目名称" prop="projectName" borderBottom ref="item1">
			<u--input :readonly="true" v-model="form.projectName" border="none" placeholder="项目名称"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
		</u-form-item>
		<u-form-item leftIcon="*" leftIconStyle="color:red;" label="项目地址" prop="projectAddress" borderBottom ref="item1">
			<u--input :readonly="true" v-model="form.projectAddress" border="none" placeholder="项目地址"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
		</u-form-item>
		<u-form-item leftIcon="*" leftIconStyle="color:red;" label="对接人" prop="recipientName" borderBottom ref="item1">
			<u--input :readonly="true" v-model="form.recipientName" border="none" placeholder="对接人"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
		</u-form-item>
		<u-form-item leftIcon="*" leftIconStyle="color:red;" label="对接人电话" prop="recipientTel" borderBottom ref="item1">
			<u--input :readonly="true" v-model="form.recipientTel" border="none" placeholder="对接人电话"></u--input>
			<u-icon slot="right" name="arrow-right"></u-icon>
		</u-form-item>
		<u-form-item leftIcon="*" leftIconStyle="color:red;" @click="serveOptionShow=true"  label="服务类别" prop="serviceTypename" borderBottom ref="item1">
			<u--input :readonly="true" v-model="form.serviceTypename" border="none" placeholder="服务类别"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
		</u-form-item>
		<view v-if="productlistShow" class="">
			<uni-table border stripe emptyText="暂无更多数据">
			    <!-- 表头行 -->
			    <uni-tr>
			        <uni-th align="center" width="100px">产品名称</uni-th>
			        <uni-th align="center" width="100px">型号</uni-th>
			        <uni-th align="center" width="60px">数量</uni-th>
											  <uni-th align="center" width="60px">日租金</uni-th>
			        <uni-th align="center" width="100px">出库数量</uni-th>
			        <uni-th align="center" width="100px">未出库数量</uni-th>
			        <uni-th align="center" width="100px">回货数量</uni-th>
			    </uni-tr>
			    <!-- 表格数据行 -->
			    <uni-tr v-for="item in productList" :key="item.id">
			        <uni-td align="center">{{item.productName}}</uni-td>
			        <uni-td align="center">{{item.model}}</uni-td>
			        <uni-td align="center">{{item.quantity}}</uni-td>
											 <uni-td align="center">{{item.dailyRent}}</uni-td>
			        <uni-td align="center">{{item.deliveryQuantity}}</uni-td>
			        <uni-td align="center">{{item.undeliveryQuantity}}</uni-td>
			        <uni-td align="center">{{item.returnQuantity}}</uni-td>
			    </uni-tr>
			</uni-table>
		</view>
		<u-form-item leftIcon="*" leftIconStyle="color:red;" @click='engineeringShow=true'  label="服务人员" prop="userName" borderBottom ref="item1">
			<u--input :readonly="true" v-model="form.userName" border="none" placeholder="服务人员"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
		</u-form-item>
		<u-form-item v-if="form.id" label="现场照片" prop="userPhoto" borderBottom ref="item1">
		<u--input disabled disabledColor="#fff" v-model="form.userPhoto" border="none" placeholder="现场照片"></u--input>
				<!-- <u-icon slot="right" name="arrow-right"></u-icon> -->
				<u-upload
						:fileList="fileList1"
						@afterRead="afterRead"
						@delete="deletePic"
						name="1"
						multiple
						:maxCount="10"
					></u-upload>
		</u-form-item>
		<u-form-item leftIcon="*" leftIconStyle="color:red;" label="情况说明" prop="salesmanRemark" borderBottom ref="item1">
			<u-textarea :readonly="true" v-model="form.salesmanRemark" border="none" placeholder="情况说明"></u-textarea>
						<u-icon slot="right" name="arrow-right"></u-icon>
		</u-form-item>
		
		<u-form-item leftIcon="*" leftIconStyle="color:red;" v-if="form.id"  label="出差天数" prop="days" borderBottom ref="item2">
			<u--input type="number" v-model="form.days" border="none" placeholder="请输入出差天数" @change="summoney"></u--input>
						<!-- <u-icon slot="right" name="arrow-right"></u-icon> -->
		</u-form-item>
		<u-form-item leftIcon="*" leftIconStyle="color:red;" v-if="form.id" label="费用" prop="costs" borderBottom ref="item3">
			<u--input  :readonly="true" v-model="form.costs" border="none" placeholder="请输入费用"></u--input>
		</u-form-item>
		<u-form-item leftIcon="*" leftIconStyle="color:red;" v-if="form.id" label="服务结果说明" prop="engineerRemark" borderBottom ref="item1">
			<u-textarea :readonly="true" v-model="form.engineerRemark" border="none" placeholder="服务结果说明"></u-textarea>
						<u-icon slot="right" name="arrow-right"></u-icon>
		</u-form-item>
	</u--form>
	
	
	
	
	<!-- 租赁订单选择框 -->
	<u-popup :show="show"  mode="right" customStyle="margin-top:44px" overlayStyle="margin-top:44px"  :closeOnClickOverlay="true" @close="show=false">
		<u--form class="orderForm" :model="orderForm" labelWidth="100px" >
			<u-form-item label="项目名" prop="projectName"  >
				<u--input v-model="orderForm.projectName"   border="none" placeholder='请选择仓库'></u--input>
			<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="客户名" prop="customerName" >
				<u--input v-model="orderForm.customerName"   border="none" placeholder='请选择仓库'></u--input>
			<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="订单状态" prop="orderStatus" @click='orderStatusShow=true'>
				<u--input v-model="orderType"  disabled disabledColor="#ffffff" border="none" placeholder='请选择仓库'>
				</u--input>
			<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-button text="查询" @click="Seacrch"></u-button>
		</u--form>
		
			<scroll-view  :scroll-y="true" class="scroll-Y" @scrolltolower="scrolltolower"  >
				 
			<view class="table" v-for="item in orderList" :key="item.id" @click="checked(item)">
				 <view>订单编号:<span class="text">{{item.orderNo}}</span></view>
				 <view>项目名:<span class="text">{{item.projectName}}</span></view>
				 <view>客户名:<span class="text">{{item.customerName}}</span> </view>
				 <view>订单状态:<span class='text'>{{item.orderStatus}}</span></view>
				 <view>创建时间:<span class="text">{{item.createTime}}</span> </view>
				 <u-button type="success" size="mini" class="button" >选择</u-button>
			
			</view>
			 
			</scroll-view>
	
		
	</u-popup>
	<u-picker @cancel="engineeringShow=false" @confirm="engConfirm" :show="engineeringShow" :columns="engineeringOptions" keyName="dictLabel"></u-picker>
	<!-- 订单状态 -->
	<u-picker @cancel="orderStatusShow=false" @confirm="confirm" :show="orderStatusShow" :columns="OrderOptions" keyName="dictLabel"></u-picker>
	<!-- 提示框 -->
		<u-modal showConfirmButton showCancelButton @confirm="BtnModel" width='250px'  @cancel="BtnShow=false" :show="BtnShow" title="提示" >
				<view class="slot-content">
					<rich-text nodes="是否确认提交?"></rich-text>
				</view>
		</u-modal>
		<u-toast ref="uToast"></u-toast>
		<!-- 服务类别 -->
		<u-picker @cancel="serveOptionShow=false" @confirm="checkServe" :show="serveOptionShow" :columns="serveOptions" keyName="dictLabel"></u-picker>
	</view>
</template>

<script>
	import {getDicts} from '@/api/dictionary/index.js'
	import {listOrder}from '@/api/order/order.js'
	import {addCost,getCost,listCost,updateCost} from '@/api/enginee.js'
	import {getLoginUser} from '@/api/system/user.js'
	import {getToken} from '@/utils/auth.js'
	import {getapprovalRecodeList,editapprovalRecode} from '@/api/approvaRecode.js'
	export default {
		data() {
			return {
				headers: {
				       Authorization: "Bearer " + getToken(),
				     },
				form:{
					applicantId:this.$store.getters.userid,
					applicantName:this.$store.getters.name,
					orderId: null,
					        orderNo: null,
					        salesman: null,
					        salesmanName: null,
					        projectName: null,
					        projectAddress: null,
					        userId: null,
					        userName: null,
					        userPhoto: null,
					        days: null,
					        costs: null,
					        delFlag: null,
					        createBy: null,
					        createTime: null,
					        updateBy: null,
					        updateTime: null,
					        remark: null,
							serviceType:'',
							recipientTel:'',
							recipientName:'',
							salesmanRemark:'',
							engineerRemark:'',
						
				},
				rules:{
					orderNo:[{required:true,message:'请选择租赁订单',trigger:['blur', 'change']}],
					salesmanName:[{required:true,message:'业务员名称',trigger:['blur', 'change']}],
					projectName:[{required:true,message:'项目名称',trigger:['blur', 'change']}],
					projectAddress:[{required:true,message:'项目地址',trigger:['blur', 'change']}],
					days:[{required:true,message:'请填写出差天数',trigger:['blur', 'change']}],
				
					engineerRemark:[{required:true,message:'请填写服务结果说明',trigger:['blur', 'change']}],
				    recipientName:[{required:true,message:'请填写对接人',trigger:['blur', 'change']}],
					recipientTel:[{required:true,message:'请填写对接人电话',trigger:['blur', 'change']}],
					serviceTypename:[{required:true,message:'请选择服务类别',trigger:['blur', 'change']}],
					userName:[{required:true,message:'请选择服务人员',trigger:['blur', 'change']}],
				    salesmanRemark:[{required:true,message:'请填写情况说明',trigger:['blur', 'change']}],
				    days:[{required:true,message:'请填写天数',trigger:['blur', 'change']}],
					costs:[{required:true,message:'请填写及费用',trigger:['blur', 'change']}],
					
				},
				show:false,
				orderForm:{
					pageNum:1,
					pageSize:3,
				},
				orderList:[],
				orderTotal:0,
				OrderOptions:[],
				orderStatusShow:false,
				fileList1:[],
				orderType:'',
				BtnShow:false,
					options1:[{text:'删除'}],
					disabledShow:true,
					
					serveOptions:[],//服务类别
					serveOptionShow:false,//服务选择
					productList:[],//订单关联产品
					productlistShow:false,
					engineeringOptions:[],
					engineeringShow:false,
					active:0
			}
		},
		onLoad(e) {
			
			this.getserveOptions()
			this.getOrderOptions()
			this.getLoginIfo()
			this.getEngineeList()
			if(JSON.stringify(e)!=="{}"){
				this.getcostInfo(e)
			}
		},
		created() {
			this.form.serialNum=this.setOrderNo()
			
		},
		onBackPress() {
			 
		},
		onShow() {
			var that=this
			uni.$on('updateData',function(data){
				console.log(data,'121');
				 that.form.userName=data.userName
				 that.form.userId=data.userId
			})
		},
		methods: {
			scrolltolower(){
				if(this.orderList.length==this.orderTotal){
					this.orderForm.pageNum=1
					return false
				}else{
					this.orderForm.pageNum++
					this.Seacrch()
				}
				
				
			},
			async getcostInfo(e){
				let res=await getCost(e.id)
				this.form=res.data
				
				 var userPhoto="http://101.132.141.5:8081"+res.data.userPhoto
				 this.fileList1.push({url:userPhoto})
				 this.form.serviceTypename=this.getValue(...this.serveOptions,this.form.serviceType)
			    let res1=await listOrder({orderNo:res.data.orderNo})
				this.productList=res1.rows[0].productList
				this.productlistShow=true
				let res2=await getapprovalRecodeList({serialNum:this.form.serialNum}) 
				this.active=0
				
				 res2.rows.forEach(item=>{
						if(item.approvalStatus==="completed"){
									this.active++
								
										}
										})
								if(this.active==1){
									this.form.days='0'
									this.form.costs='0'
								} 	
			},
			getValue(arr, item) {
			    for (var i = 0; i < arr.length; i++) {
			        if (item == arr[i].dictValue) {
			            return arr[i].dictLabel
			        }
			    }
			},
			// 获取订单编号
			setOrderNo() {
			    var date = new Date();
			    var year = date.getFullYear(); //年 ,从 Date 对象以四位数字返回年份
			    var month = date.getMonth() + 1; //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
			    var day = date.getDate(); //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)
			    //修改月份格式
			    if (month >= 1 && month <= 9) {
			        month = "0" + month;
			    }
			    //修改日期格式
			    if (day >= 0 && day <= 9) {
			        day = "0" + day;
			    }
			
			    let round = Math.floor(Math.random() * (999 - 100)) + 100;
			    var currentFormatDate = `${year}${month}${day}`;
			    return "GCBGL" + currentFormatDate + round;
			},
			summoney(){
				this.form.costs=0
				this.form.costs=this.form.days*500
				this.form.costs= this.form.costs.toString()
				  
			},
			 // 工程部人员
			 async getEngineeList(){
				 let res=await getDicts('engineering')
				 this.engineeringOptions.push(res.data)
			 },
			 // 选中
			 engConfirm(val){
				 console.log(val);
				 this.engineeringShow=false
				 this.form.userName=val.value[0].dictLabel
				 this.form.userId=val.value[0].dictValue
			 },
			 
		  
			// 获取服务类别
			async getserveOptions(){
				let res= await getDicts('serve_type')
				this.serveOptions.push(res.data)
			},
		  checkServe(val){
				this.serveOptionShow=false
				
				// 选择服务类别后
			     listOrder({orderNo:this.form.orderNo}).then(res=>{
					 if(res.rows.length!==1){
					 	 this.$refs.uToast.show({
					 		 type:'error',
					 		 message:'请先选择订单'
					 	 })
					 }else{
						 this.form.serviceType=val.value[0].dictValue
						 this.form.serviceTypename=val.value[0].dictLabel
					 	this.productList=res.rows[0].productList
					 	this.productlistShow=true
					 }
				 })
				
				
			},
			// 删除图片
			deletePic(event) {
							this[`fileList${event.name}`].splice(event.index, 1)
						},
						// 新增图片
				async afterRead(event) {
							// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
							let lists = [].concat(event.file)
							let fileListLen = this[`fileList${event.name}`].length
							lists.map((item) => {
								this[`fileList${event.name}`].push({
									...item,
									status: 'uploading',
									message: '上传中'
								})
								 
							})
							for (let i = 0; i < lists.length; i++) {
								console.log();
								const result = await this.uploadFilePromise(lists[i].url)
								
								let item = this[`fileList${event.name}`][fileListLen]
								this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
									status: 'success',
									message: '附件图片',
									url: result
								}))
								fileListLen++
							}
							
							 
							console.log(this.fileList1);
						},
							uploadFilePromise(url) {
										return new Promise((resolve, reject) => {
											let a = uni.uploadFile({
												url: 'http://101.132.141.5:8081/common/upload', // 仅为示例，非真实的接口地址
												filePath: url,
												header:this.headers,
												name: 'file',
												form: {
													user: 'test'
												},
									 
												success: (res) => {
													console.log(res);
													console.log(JSON.parse(res.data));
													this.form.userPhoto=JSON.parse(res.data).fileName
													console.log(this.form.userPhoto);
													setTimeout(() => {
														resolve(res.data.data)
														 
													}, 1000)
													console.log(a);
												}
											});
										})
									},
			
			// 获取用户信息
			async getLoginIfo(){
				let res=await getLoginUser()
				      console.log(res)
				      // this.form.userId=res.user.userId
				      // this.form.userName=res.user.username
			},
			// 打开弹框
			async openPop(){
				this.show=true
				let res=await listOrder(this.orderForm)
				res.rows.forEach(item=>{
					item.orderStatus=this.getValue(...this.OrderOptions,item.orderStatus)
				})
				this.orderList=res.rows
			},
			getValue(arr, item) {
			      for (let i = 0; i < arr.length; i++) {
			        if (item === arr[i].dictValue) {
			          return arr[i].dictLabel
			        }
			      }
			    },
				//获取租赁订单状态
				async getOrderOptions(){
				  let res=await getDicts('order_type')
				  this.OrderOptions.push(res.data)
				},
				confirm(val){
					 
					this.orderStatusShow=false
					this.orderForm.orderStatus=val.value[0].dictValue
					this.orderType=val.value[0].dictLabel
					console.log(this.orderForm.orderStatus);
				},
				async Seacrch(){
					let res=await listOrder(this.orderForm)
					res.rows.forEach(item=>{
						item.orderStatus=this.getValue(...this.OrderOptions,item.orderStatus)
					})
					this.orderList.push(...res.rows)
				},
				// 选择订单
				checked(val){
					 
					    this.form.orderNo=val.orderNo
						this.form.orderId=val.orderId
					      this.form.salesmanName=val.salesmanName
					      this.form.salesman=val.salesman
					      this.form.projectName=val.projectName
					      this.form.projectAddress=val.address
						  this.form.recipientName=val.consigneeName
						  this.form.recipientTel=val.consigneeTel
					this.show=false
				},
				// 保存订单
				btnOk(){
					
					try{
						if(this.form.id){
							
							 this.$refs.form.validate().then(async(res)=>{
							 	if(res){
							 		this.BtnShow=true
							 		}
							 })
							 
							 
							
						}else{
							// 新增
							this.form.days=0
							this.form.costs=0
							this.form.engineerRemark='~'
							this.$refs.form.validate().then(async(res)=>{
									if(res){
											this.BtnShow=true
														  }
							})
						}
						 
						
					}catch(error){
						this.$refs.uToast.show({
							type:'warning',
							message:'请检查信息是否填写完整'
						})
					}
				},
				async BtnModel(){
					this.BtnShow=false
					 
					if(this.form.id){
						await updateCost(this.form)
							var that=this
						this.$refs.uToast.show({
							type:'success',
							message:"修改成功",
						
							complete(){
								if(that.active==1 || that.active==2){
									  editapprovalRecode({serialNum:that.form.serialNum,typeOperation:'agree'})
								}
								uni.redirectTo({
									url:'/pages/ebgineeCost/engineedatial/engineedatial?item='+encodeURIComponent(JSON.stringify(that.form))
								})
							}
						})
					}else {
						await addCost(this.form)
						let res=await listCost({serialNum:this.form.serialNum})
						this.form=res.rows[0]
						console.log(this.form,'add');
						var that=this
						this.$refs.uToast.show({
							type:'success',
							message:"新增成功",
							complete(){
								 
								uni.redirectTo({
									url:'/pages/ebgineeCost/engineedatial/engineedatial?item='+encodeURIComponent(JSON.stringify(that.form))
								})
							}
						})
					}
					
					
					
					
				},
				// 删除
				delFn(id){
					delLogistApi(id).then(response=>{
						console.log(response);
						if(response.code==200){
							this.$refs.uToast.show({
								type:'success',
								message:'删除成功!'
							})
						}
						this.initData()
					})
				},
			back(){
			uni.navigateBack({delta:1})
			}
		}
	}
</script>

<style lang="scss">
.form{
	   background-color: #fff;
	   padding-left: 10px;
	   padding-right: 10px;
   }
   .orderForm{
	   margin-left: 8px;
   }
   .table{
   	   position: relative;
   	   border: 1px solid #ccc;
   	   margin: 5px;
   	   padding-left: 5px;
   	   .button{
   		   width: 50px;
   		   position: absolute;
   		   bottom: 10px;
   		   right: 10px;
   	   }
   	   .text{
   		   
   		font-size: 14px;
   		   color: #969696;
   	   }
   }
</style>
